package com.atguigu.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.bean.TableProcessDim;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.FlinkSourceUtil;
import com.atguigu.gmall.realtime.common.util.HBaseUtil;
import com.atguigu.gmall.realtime.dim.function.HbaseSinkFunction;
import com.atguigu.gmall.realtime.dim.function.TableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;


/**
 * ClassName: DimApp
 * Description:
 *
 * @Create 2024/4/16 11:42
 */
public class DimApp extends BaseApp {
    public static void main(String[] args) throws Exception {
        new DimApp().start(10001,4,"dim_app",Constant.TOPIC_DB);
    }


    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaSourceDS) {

        //TODO 4.对读取的数据类型转换并进行ETL清洗  JSON -> jsonObj
        //优化Ctrl + Alt + M
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaSourceDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                        try {
                            //将读取到的字符串转换为json对象
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            //获取操作的数据库名称
                            String db = jsonObj.getString("database");
                            //获取操作类型
                            String type = jsonObj.getString("type");
                            //获取当前操作影响的一条数据
                            String data = jsonObj.getString("data");
                            //ETL
                            if ("gmall1030".equals(db)
                                    && ("insert".equals(type)
                                    || "update".equals(type)
                                    || "delete".equals(type)
                                    || "bootstrap-insert".equals(type))
                                    && data != null
                                    && data.length() > 2) {
                                collector.collect(jsonObj);
                            }
                        } catch (Exception e) {
                            throw new RuntimeException("不是一个标准json");
                        }
                    }
                }
        );


        //TODO 5.使用FlinkCDC读取配置表中的配置信息
        //5.1 CDC读取配置表信息
        //优化2
        MySqlSource<String> mySqlSource = FlinkSourceUtil.getMySqlSource("gmall1030_config", "gmall1030_config.table_process_dim");
        //5.2 读取数据封装为流
        DataStreamSource<String> mysqlStrDS = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);


        //TODO 6.对读取的配置流数据进行类型转换  JSON -> 实体类对象
        SingleOutputStreamOperator<TableProcessDim> tpDS = mysqlStrDS.map(
                new MapFunction<String, TableProcessDim>() {
                    @Override
                    public TableProcessDim map(String jsonStr) throws Exception {
                        //为了处理方便，先将jsonStr转为jsonObj
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        //获取对配置表中数据进行的操作类型
                        String op = jsonObj.getString("op");
                        TableProcessDim tableProcessDim = null;
                        if ("d".equals(op)) {
                            //fastJson底层自动做了下划线 -> 驼峰命名转换
                            tableProcessDim = jsonObj.getObject("before", TableProcessDim.class);
                        } else {
                            tableProcessDim = jsonObj.getObject("after", TableProcessDim.class);
                        }
                        tableProcessDim.setOp(op);
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);


        //TODO 7.根据配置流中的数据，到Hbase中执行建表或者删除操作
        tpDS = tpDS.map(
                new RichMapFunction<TableProcessDim, TableProcessDim>() {

                    Connection hBaseConnection;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        hBaseConnection = HBaseUtil.getHBaseConnection();
                    }

                    @Override
                    public void close() throws Exception {
                        HBaseUtil.closeHBaseConn(hBaseConnection);
                    }

                    @Override
                    public TableProcessDim map(TableProcessDim tableProcessDim) throws Exception {
                        //获取对配置表中数据的操作类型
                        String op = tableProcessDim.getOp();

                        //获取要操作的Hbase表名字
                        String sinkTable = tableProcessDim.getSinkTable();

                        //获取再Hbase中建表的列族
                        String[] famlies = tableProcessDim.getSinkFamily().split(",");

                        if ("r".equals(op) || "c".equals(op)) {
                            //创建Hbase表
                            HBaseUtil.createHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE,sinkTable,famlies);
                        } else if ("d".equals(op)) {
                            //删除Hbase表
                            HBaseUtil.dropHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE,sinkTable);
                        } else {
                            //先将Hbase表删除，再创建
                            HBaseUtil.dropHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE,sinkTable);
                            HBaseUtil.createHBaseTable(hBaseConnection,Constant.HBASE_NAMESPACE,sinkTable,famlies);
                        }

                        return tableProcessDim;
                    }
                }
        );


        //TODO 8.将配置流进行广播--broadcast
        MapStateDescriptor<String, TableProcessDim> mapStateDescriptor =
                new MapStateDescriptor<String, TableProcessDim>("mapStateDescriptor",String.class,TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastDS = tpDS.broadcast(mapStateDescriptor);


        //TODO 9.将主流业务数据与广播流配置信息进行关联--connect
        BroadcastConnectedStream<JSONObject, TableProcessDim> connectDS = jsonObjDS.connect(broadcastDS);


        //TODO 10.对关联后的数据进行处理--process()
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> processDS = connectDS.process(
                new TableProcessFunction(mapStateDescriptor)
        );


        //TODO 11.将维度数据同步Hbase表中
        processDS.addSink(new HbaseSinkFunction());
    }
}
